package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.Admin;
import com.atguigu.service.AdminService;
import com.atguigu.service.RoleService;
import com.atguigu.util.QiniuUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {

    private static final String PAGE_INDEX = "admin/index";
    private static final String PAGE_CREATE = "admin/create";
    private static final String ACTION_LIST = "redirect:/admin";
    private static final String PAGE_EDIT = "admin/edit";
    private static final String PAGE_UPLOAD_SHOW = "admin/upload";
    private static final String PAGE_ASSIGN_ROLE = "admin/assignShow";
    @Reference
    AdminService adminService;

    @Reference
    RoleService roleService;

    @Autowired
    PasswordEncoder passwordEncoder;


    @RequestMapping("/assignRole")
    @PreAuthorize("hasAuthority('admin.assgin')")
    public String assignRole(Long adminId,Long[] roleIds,HttpServletRequest request){
        //注意：操作中间表数据，通过多对多两端任意服务接口都行。中间表不提供业务接口
        roleService.assignRole(adminId, roleIds);

        return this.successPage(null, request);
    }
    /**
     *
     * @param id 用户主键
     * @return 去分配页面 准备两个下拉集合
     */
    @PreAuthorize("hasAuthority('admin.assgin')")
    @RequestMapping("/assignRole/{id}")
    public String assignRole(@PathVariable("id") Long id,Map map){
        //map中存放的是两个下拉列选集合
        Map assignMap = roleService.getSelectByAdminId(id);
        map.putAll(assignMap);
        map.put("adminId", id);
        return PAGE_ASSIGN_ROLE;

    }


    @GetMapping("/uploadShow/{id}")
    public String uploadShow(ModelMap model, @PathVariable Long id) {
        model.addAttribute("id", id);
        return PAGE_UPLOAD_SHOW;
    }

    @PostMapping("/upload/{id}")
    public String upload(@PathVariable Long id, @RequestParam(value = "file") MultipartFile file, HttpServletRequest request) throws IOException {
        String newFileName =  UUID.randomUUID().toString() ;
        // 上传图片
        QiniuUtils.upload2Qiniu(file.getBytes(),newFileName);
        String url= "http://rdv1ostyt.hn-bkt.clouddn.com/"+ newFileName;
        Admin admin = new Admin();
        admin.setId(id);
        admin.setHeadUrl(url);
        adminService.update(admin);
        return this.successPage(this.MESSAGE_SUCCESS, request);
    }

    @PreAuthorize("hasAuthority('admin.delete')")
    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") Long id) {
        adminService.delete(id);
        return ACTION_LIST;
    }

    @PreAuthorize("hasAuthority('admin.edit')")
    @RequestMapping("/edit/{id}")
    public String edit(Model model, @PathVariable("id") Long id) {
        Admin admin = adminService.getById(id);
        model.addAttribute("admin", admin);
        return PAGE_EDIT;
    }

    @PreAuthorize("hasAuthority('admin.edit')")
    @RequestMapping("/update")
    public String update(Admin admin, Map  map,HttpServletRequest request) {
        adminService.update(admin);
        return this.successPage("修改成功",request);
    }

    @RequestMapping("/save")
    @PreAuthorize("hasAuthority('admin.create')")
    public String save(Admin admin, Map  map,HttpServletRequest request){//SpringMVC框架根据反射创建bean对象，并调用参数名称的set方法，将参数封装到bean对象中
        admin.setHeadUrl("http://47.93.148.192:8080/group1/M00/03/F0/rBHu8mHqbpSAU0jVAAAgiJmKg0o148.jpg");
        admin.setPassword(passwordEncoder.encode(admin.getPassword()));
        adminService.insert(admin);
        return this.successPage("添加成功",request);
    }
    @PreAuthorize("hasAuthority('admin.create')")
    @RequestMapping("/create")
    public String create(){

        return PAGE_CREATE;
    }

//    @RequestMapping
//    public String index(Model model) {
//        List<Admin> list = adminService.findAll();
//
//        model.addAttribute("list", list);
//
//        return PAGE_INDEX;
//    }

    /**
     * 分页查询
     * 查询条件进行查询
     *  adminName = ''
     *  pageNum = 1  隐藏域
     *  pageSize = 10 隐藏域
     * @param model
     * @return
     */
    @RequestMapping
    @PreAuthorize("hasAuthority('admin.show')")
    public String index(HttpServletRequest request,Model model) {
        Map<String, Object> filters = getFilters(request);
        //分页对象，将集合的数据，pageNum，pageSize，pages，total等
        PageInfo<Admin> pageInfo = adminService.findPage(filters);
        model.addAttribute("page", pageInfo);
        model.addAttribute("filters", filters);
        return PAGE_INDEX;
    }


}
